const path = require('path')
const fs = require('fs')
const cp = require('child_process')



function getBookmarks() {
    const platform = process.platform
    let bookmarksData = []
    if (platform === 'darwin') {
        bookmarkPath = path.join("/Users/liuyongliang/Library/Application\ Support/Google/Chrome/Default/Bookmarks")
        const browser = "chrome"
        const icon = browser + '.png'
        try {
            const data = JSON.parse(fs.readFileSync(bookmarkPath, 'utf-8'))
            const getUrlData = (item, folder) => {
                if (!item || !Array.isArray(item.children)) return
                item.children.forEach(c => {
                    if (c.type === 'url') {
                        bookmarksData.push({
                            featureName: c.name || '',
                            featureDesc: (folder ? '「' + folder + '」' : '') + c.url,
                            pluginName: "书签",
                            featureIcon: icon, // 图标
                            extInfo: {
                                addAt: parseInt(c.date_added),
                                title: c.name || '',
                                description: (folder ? '「' + folder + '」' : '') + c.url,
                                url: c.url,
                                browser,
                                icon
                            }
                        })
                    } else if (c.type === 'folder') {
                        getUrlData(c, folder ? folder + ' - ' + c.name : c.name)
                    }
                })
            }
            getUrlData(data.roots.bookmark_bar, '')
            getUrlData(data.roots.other, '')
            getUrlData(data.roots.synced, '')
        } catch (e) { console.info("e", e) }

    } else { return [] }
    if (bookmarksData.length > 0) {
        bookmarksData = bookmarksData.sort((a, b) => a.addAt - b.addAt)
    }
    return bookmarksData
}

function openUrlByChrome(url) {
    if (process.platform === 'darwin') {
        const chromeApp = '/Applications/Google Chrome.app'
        if (fs.existsSync(chromeApp)) {
            cp.spawn('open', ['-a', chromeApp, url], { detached: true })
        } else {
            window.utools.shellOpenExternal(url)
        }
    }
}


const electron = require('electron')

electron.contextBridge.exposeInMainWorld('api', {
    getBookmarks: () => {
        return getBookmarks()
    },
    openUrlByChrome: (url) => {
        return openUrlByChrome(url)
    },
})